package com.turing.post.account.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.account.util.SalesGroup;
import com.turing.post.account.util.SalesGroupDao;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

@Stateless(mappedName = "account.impl.SalesGroupDaoImpl")
@Remote
@Local
public class SalesGroupDaoImpl implements SalesGroupDao {
	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	/**
	 * 插入销售员组记录
	 * 
	 * @param sac
	 * @throws PCPSApplicationException
	 */
	public void insert(SalesGroup sg) throws PCPSApplicationException {
		GeneralDao.insert(_em, sg);
	}

	/**
	 * 根据销售员ID、贡献度、组内hash检索本组所有销售员贡献度列表
	 * 
	 * @param salesGroupId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<SalesGroup> getAllSalesGroupBySalesId(BigInteger salesId,
			BigInteger salesGroupHash, BigInteger degreeOfcontribution) {
		Query query = _em
				.createNativeQuery(
						"select m.* from SalesGroup m where m.salesGroupId in "
								+ "( select t.salesGroupId from SalesGroup t where t.salesId =?1 and t.salesGroupHash = ?2 and t.degreeOfcontribution = ?3) "
								+ "order by m.salesGroupId, m.salesId",
						SalesGroup.class);
		query.setParameter(1, salesId);
		query.setParameter(2, salesGroupHash);
		query.setParameter(3, degreeOfcontribution);
		return query.getResultList();
	}

	/**
	 * 根据销售员组ID检索本组所有销售员贡献度列表
	 * 
	 * @param salesGroupId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<SalesGroup> getAllSalesGroupBySalesGroupId(
			BigInteger salesGroupId) {
		Query query = _em
				.createNativeQuery(
						"select t.* from SalesGroup t where t.salesGroupId = ?1 order by t.salesId",
						SalesGroup.class);
		query.setParameter(1, salesGroupId);
		return query.getResultList();
	}

}